<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="realSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="文件名称" prop="fileName">
            <el-input
              v-model="baTable.form.items!.fileName"
              placeholder="请输入文件名称"
            />
          </el-form-item>
          <el-form-item label="材料文件" prop="fileUrl">
            <el-upload
              ref="uploadPdfRef"
              v-model:file-list="pdfFileList"
              :limit="1"
              accept=".doc,.docx,.xlsx,.pdf,.jpg,.png,.jpeg"
              class="upload-demo"
              :action="state.fileAction1"
              :auto-upload="false"
              :on-change="changUploadPdf"
              :on-remove="handleRemovePdf"
            >
              <el-button type="primary">上传本地文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持doc、docx、xlsx、pdf 、jpg等常见文件格式
                </div>
              </template>
            </el-upload>
            <el-link
              @click="equipSpecifications(baTable.form.items!.fileUrl)"
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              >{{ baTable.form.items!.fileUrl }}</el-link
            >
          </el-form-item>
          <el-form-item label="视频文件" prop="videoUrl">
            <el-upload
              ref="uploadVideoRef"
              v-model:file-list="pdfFileList"
              :limit="1"
              accept=".mp4"
              class="upload-demo"
              :action="state.fileAction1"
              :auto-upload="false"
              :on-change="changUploadVideo"
              :on-remove="handleRemoveVideo"
            >
              <el-button type="primary">上传本地视频</el-button>
              <template #tip>
                <div class="el-upload__tip">支持mp4等常见视频格式</div>
              </template>
            </el-upload>
            <el-link
              @click="equipSpecifications(baTable.form.items!.videoUrl)"
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              >{{ baTable.form.items!.videoUrl }}</el-link
            >
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="realSubmit(formRef)"
          type="primary"
        >
          {{ baTable.form.operate === "add" ? "保存并添加下一项" : "保存" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  reactive,
  ref,
  inject,
  onMounted,
  computed,
  watch,
  nextTick,
} from "vue";
import type baTableClass from "@/utils/baTable";
import type {
  ElForm,
  FormRules,
  ElTree,
  UploadFile,
  UploadFiles,
  UploadProgressEvent,
  FormInstance,
} from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { getRegionName } from "@/utils/common";
import { _download, _upload } from "@/utils/axios";
import { getPointByAddress } from "vue-baidu-map-3x"; //baidu-map组件red
import { useConfig } from "@/store/config"; //后台布局相关仓库
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useRoute, useRouter } from "vue-router";
import type {
  UploadProps,
  UploadUserFile,
  UploadInstance,
  UploadRequestOptions,
} from "element-plus";
import { ElNotification } from "element-plus"; //处理导航信息

type Option = {
  id: number;
  label: string;
  children: Option[];
};

//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const formRef = ref<InstanceType<typeof ElForm>>();
const config = useConfig();
const route = useRoute();
const { proxy } = useCurrentInstance();
const uploadPdfRef = ref<UploadInstance>();
const uploadVideoRef = ref<UploadInstance>();

const fileList = ref<UploadUserFile[]>([
  //   {
  //     name: "",
  //     url: "",
  //   },
]);

const state: {
  form: anyObj;
  fileAction1: string;
  fileAction2: string;
  fileAction3: string;
  host: string;
} = reactive({
  form: {
    brand: "",
    certificate: "",
    electricfield: "",
    information: "",
    name: "",
    pic: "",
    power: "",
    rate: "",
    report: "",
    type: "",
    volume: "",
    // fanPressure: "",
    flowRate: "",
    sectionalArea: "",
  },
  fileAction1: "", //上传pdf文件的服务器地址
  fileAction2: "",
  fileAction3: "",
  host: "",
});

//视频文件
const videoFileList = ref<UploadUserFile[]>([]);
const videoRealFileList = ref<UploadUserFile[]>([]);

//材料pdf
const pdfFileList = ref<UploadUserFile[]>([]);
const pdfRealUploadFile = ref<UploadUserFile[]>([]);

const headerConfig = {
  Authorization: JSON.parse(localStorage.getItem("adminInfo") as any)?.token,
};

//移除材料pdf
const handleRemovePdf: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles, pdfFileList);
  const { uid } = uploadFile;
  const selectFileList = pdfFileList.value.filter((item) => {
    return item.uid != uid;
  });
  pdfFileList.value = selectFileList;
};
//设备说明书pdf文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUploadPdf: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  baTable.form.loading = true;
  console.log("文件限制", uploadFile, uploadFiles, pdfFileList);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
    });
    const selectFileList = pdfFileList.value.filter((item) => {
      return item.uid != uid;
    });
    pdfFileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = pdfFileList.value.filter((item) => {
      return item.uid != uid;
    });
    pdfFileList.value = selectFileList;
    return;
  }
  // 将上传PDF说明书文件信息存入列表
  pdfFileList.value.push(uploadFile);
  pdfRealUploadFile.value = [];
  let formData = new FormData();
  formData.append("file", uploadFiles[0].raw as any); //添加文件对象
  formData.append("name", "pdf"); //添加文件对象
  _upload("/common/upload", formData, "").then((res: any) => {
    // baTable.form.items!.information = res.data.url;
    // baTable.form.items!.fileUrl =
    //   state.host === "" ? res.data.url : state.host + res.data.fileName;
    baTable.form.items!.fileUrl =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
    // baTable.form.items!.fileUrl = res.data.url;
    baTable.form.loading = false;
  });
};
//允许自行实现上传文件的请求 再用户触发了realSubmit后触发
// const handleUplodFilePdf = (options: UploadRequestOptions) => {
//   console.log("允许自行实现上传文件的请求", options);
//   pdfRealUploadFile.value.push(options.file);
//   let formData = new FormData();
//   formData.append("file", options.file); //添加文件对象
//   formData.append("name", "pdf"); //添加文件对象
//   _upload("/common/upload", formData, "").then((res: any) => {
//     state.form.information = res.data.url;
//     //再上传cep图片
//     uploaCepfRef.value!.submit();
//   });
// };

//移除视频文件
const handleRemoveVideo: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles, videoFileList);
  const { uid } = uploadFile;
  const selectFileList = videoFileList.value.filter((item) => {
    return item.uid != uid;
  });
  videoFileList.value = selectFileList;
};
//视频文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUploadVideo: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  baTable.form.loading = true;
  console.log("文件限制", uploadFile, uploadFiles, videoFileList);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.mp4|.mp5$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.doc|.docx|.xlsx|.pdf|.jpg|.jpeg|.png",
    });
    const selectFileList = videoFileList.value.filter((item) => {
      return item.uid != uid;
    });
    videoFileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = videoFileList.value.filter((item) => {
      return item.uid != uid;
    });
    videoFileList.value = selectFileList;
    return;
  }
  // 将上传PDF说明书文件信息存入列表
  videoFileList.value.push(uploadFile);
  videoRealFileList.value = [];
  let formData = new FormData();
  formData.append("file", uploadFiles[0].raw as any); //添加文件对象
  formData.append("name", "pdf"); //添加文件对象
  _upload("/common/upload", formData, "").then((res: any) => {
    // baTable.form.items!.information = res.data.url;
    // baTable.form.items!.fileUrl =
    //   state.host === "" ? res.data.url : state.host + res.data.fileName;
    baTable.form.items!.videoUrl =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
    // baTable.form.items!.fileUrl = res.data.url;
    baTable.form.loading = false;
  });
};

//规则
const rules = reactive<FormRules>({
  fileName: [{ required: true, message: "文件名称不能为空", trigger: "blur" }],
  fileUrl: [{ required: true, message: "材料文件不能为空", trigger: "blur" }],
});

//提交表单
const realSubmit = (formEl: FormInstance | undefined) => {
  baTable.form.items.orderId = route.query.orderId; //文件名对应的id
  baTable.form.items.companyId = route.query.companyId; //企业id
  nextTick(() => {
    baTable.onSubmit(formRef.value);
  });
};

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});
//地址转换为坐标 北京市海淀区上地十街10号
// const pointAndAddress = () => {
//   getPointByAddress(
//     {
//       address: baTable.form.items!.addr,
//     },
//     ["wZcU7ugfOpZLuuRTAvNPn3Y36rpFxp1Q"]
//   )
//     .then((res) => {
//       let { location, formatted_address } = res as any;
//       baTable.form.items!.coordinate = JSON.stringify(location);
//     })
//     .catch((err: any) => {
//       console.log(err);
//       ElNotification({
//         type: "warning",
//         message: err + ",请检查并填写正确企业地址",
//       });
//       baTable.form.items!.addr = "";
//       baTable.form.items!.coordinate = "";
//       baTable.form.items!.institution = 0;
//     });
// };

const equipSpecifications = (url: any) => {
  window.open(url);
};

//获取域名进行拼接
const getBaseUrl = () => {
  let url = window.location;
  console.log("获取域名进行拼接", url.origin, url.origin.includes("s"));
  if (url.origin.includes("180")) {
    //https
    state.host = url.origin;
  } else {
    state.host = "";
  }
};
getBaseUrl();

onMounted(() => {
  console.log("route", route.query);
});
// defineExpose({
//   getCheckeds,
// });
// watch(filterText, (val) => {
//   treeRef2.value!.filter(val);
// });
// watch(filterTextIOT, (val) => {
//   treeRef3.value!.filter(val);
// });
</script>
<style lang="scss" scoped>
.filter-tree {
  height: 200px;
}
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  height: v-bind(overviewMenusScrollbarHeight);
}
</style>
